package admin

import (
	"chaowan/data_source"
	"chaowan/models"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

type BuykuangshilistRBody struct {
	Data       []models.Buydaibisql `json:"data"`
	PageNo     int                  `json:"pageNo"`
	PageSize   int                  `json:"pageSize"`
	TotalCount int64                `json:"totalCount"`
	TotalPage  int64                `json:"totalPage"`
}

type BuysBody struct {
	Page     int    `json:"page"`
	Pagesize int    `json:"pagesize"`
	Inttime  int64  `json:"inttime"`
	Endtime  int64  `json:"endtime"`
	Daytime  int64  `json:"daytime"`
	Laiyuan  int64  `json:"laiyuan"`
	Phone    string `json:"phone"`
	State    int64  `json:"state" gorm:"state"`       // 1充值代币2扭蛋机购买 3一番赏购买 4商品购买 5支付运费
	Paystate int64  `json:"paystate" gorm:"paystate"` // 1微信 2支付宝 3微信小程序
}

func Buykuangshilist(ctx *gin.Context) {
	request := BuysBody{}
	ctx.ShouldBind(&request)

	laiyuan := request.Laiyuan
	phone := request.Phone
	inttime := request.Inttime
	endtime := request.Endtime
	currentPage := request.Page
	pageSize := request.Pagesize
	offsetNum := pageSize * (currentPage - 1)
	var count int64
	var orders []models.Buydaibisql
	res := data_source.Db.Model(&models.Buydaibi{}).Select("buydaibi.*, user.nickname, user.phone, package.price, package.daibi, user.laiyuan").Joins("left join user on user.id = buydaibi.uid").Joins("left join package on package.id = buydaibi.packageid").Where("buydaibi.status = ?", 2)
	if inttime > 0 {
		res = res.Where("buydaibi.addtime >= ?", inttime)
	}
	if endtime > 0 {
		res = res.Where("buydaibi.addtime < ?", endtime)
	}
	if phone != "" {
		res = res.Where("user.phone = ?", phone)
	}
	if laiyuan > 0 {
		res = res.Where("user.laiyuan = ?", laiyuan)
	}
	res.Model(&models.Buydaibi{}).Count(&count)
	res.Limit(pageSize).Offset(offsetNum).Order("id desc").Find(&orders)

	var totalPage int64
	mo := count % int64(pageSize)
	if mo > 0 {
		totalPage = count/int64(pageSize) + 1
	} else {
		totalPage = count / int64(pageSize)
	}
	data := BuykuangshilistRBody{
		Data:       orders,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return
}

type BuyczlistRBody struct {
	Data       []models.Userchongzhisql `json:"data"`
	PageNo     int                      `json:"pageNo"`
	PageSize   int                      `json:"pageSize"`
	TotalCount int64                    `json:"totalCount"`
	TotalPage  int64                    `json:"totalPage"`
}

func Buyczlist(ctx *gin.Context) {
	request := BuysBody{}
	ctx.ShouldBind(&request)

	laiyuan := request.Laiyuan
	state := request.State
	paystate := request.Paystate
	phone := request.Phone
	inttime := request.Inttime
	endtime := request.Endtime
	currentPage := request.Page
	pageSize := request.Pagesize
	offsetNum := pageSize * (currentPage - 1)
	var count int64
	var orders []models.Userchongzhisql
	res := data_source.Db.Model(&models.Userchongzhi{}).Select("userchongzhi.*, user.nickname, user.phone, user.laiyuan").Joins("left join user on user.id = userchongzhi.uid")
	if state > 0 {
		res = res.Where("userchongzhi.state = ?", state)
	}
	if paystate > 0 {
		res = res.Where("userchongzhi.paystate = ?", paystate)
	}
	if inttime > 0 {
		res = res.Where("userchongzhi.addtime >= ?", inttime)
	}
	if endtime > 0 {
		res = res.Where("userchongzhi.addtime < ?", endtime)
	}
	if phone != "" {
		res = res.Where("user.phone = ?", phone)
	}
	if laiyuan > 0 {
		res = res.Where("user.laiyuan = ?", laiyuan)
	}
	res.Model(&models.Userchongzhi{}).Count(&count)
	res.Limit(pageSize).Offset(offsetNum).Order("id desc").Find(&orders)

	var totalPage int64
	mo := count % int64(pageSize)
	if mo > 0 {
		totalPage = count/int64(pageSize) + 1
	} else {
		totalPage = count / int64(pageSize)
	}
	data := BuyczlistRBody{
		Data:       orders,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return
}

type UserbblistBody struct {
	Daytime int64 `json:"daytime"`
	Inttime int64 `json:"inttime"`
	Endtime int64 `json:"endtime"`
	State   int64 `json:"state" gorm:"state"` // 1注册 2付费 3复购 4活跃  5arup
}
type UserzcRBody struct {
	Daytime   string `json:"daytime"`   //今天时间
	Daynum    int64  `json:"daynum"`    //今天注册
	Iosnum    int64  `json:"iosnum"`    //今天ios注册
	Anzhuonum int64  `json:"anzhuonum"` //今天安卓注册
	Weixinnum int64  `json:"weixinnum"` //今天小程序注册
}
type UserffRBody struct {
	Daytime     string  `json:"daytime"`     //今天时间
	Dayprice    float64 `json:"dayprice"`    //今天充值
	Iosprice    float64 `json:"iosprice"`    //今天ios充值
	Anzhuoprice float64 `json:"anzhuoprice"` //今天安卓充值
	Weixinprice float64 `json:"weixinprice"` //今天小程序充值
}

type UserfgRBody struct {
	Daytime       string `json:"daytime"`       //今天时间
	Onenum        int64  `json:"onenum"`        //充值1次人数
	Twonum        int64  `json:"twonum"`        //充值2次人数
	Threenum      int64  `json:"threenum"`      //充值3次人数
	Fournum       int64  `json:"fournum"`       //充值4次人数
	Fivenum       int64  `json:"fivenum"`       //充值5次人数
	Exceedfivenum int64  `json:"exceedfivenum"` //充值超过5次人数
}

type UserhyRBody struct {
	Dayhynum   int64 `json:"dayhynum"`   //今天活跃用户
	Weekhynum  int64 `json:"weekhynum"`  //本周活跃用户
	Monthhynum int64 `json:"monthhynum"` //本月活跃用户
}

type UserarupRBody struct {
	Daytime     string  `json:"daytime"`     //今天时间
	Averagearup float64 `json:"averagearup"` //平均arup
	Buyarup     float64 `json:"buyarup"`     //付费arup
}

type UserfglistRBody struct {
	Uid int64 `json:"uid"` //
	Num int64 `json:"num"`
}

func Userbblist(ctx *gin.Context) {
	request := UserbblistBody{}
	ctx.ShouldBind(&request)

	daytime := request.Daytime

	if daytime == 0 {
		now := time.Now()
		daytime = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()).Unix()
	}
	state := request.State

	daytimeval := time.Unix(daytime, 0).Format("2006-01-02")
	if state == 1 {
		var daynum int64
		var iosnum int64
		var anzhuonum int64
		var weixinnum int64
		var users []models.User
		data_source.Db.Where("create_time >= ?", daytime).Where("create_time < ?", daytime+86400).Find(&users)
		for _, v := range users {
			daynum = daynum + 1
			if v.Qudao == "weixin" {
				weixinnum = weixinnum + 1
			} else if v.Qudao == "ios" {
				iosnum = iosnum + 1
			} else {
				anzhuonum = anzhuonum + 1
			}
		}
		data := UserzcRBody{
			Daytime:   daytimeval,
			Daynum:    daynum,
			Iosnum:    iosnum,
			Anzhuonum: anzhuonum,
			Weixinnum: weixinnum,
		}
		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"error":   0,
			"success": 200,
			"data":    data,
			"msg":     "ok",
		})
		return
	} else if state == 2 {
		var dayprice float64
		var iosprice float64
		var anzhuoprice float64
		var weixinprice float64
		var users []models.Userchongzhi
		data_source.Db.Where("addtime >= ?", daytime).Where("addtime < ?", daytime+86400).Find(&users)
		for _, v := range users {
			dayprice = dayprice + v.Price
			if v.Qudao == "weixin" {
				weixinprice = weixinprice + v.Price
			} else if v.Qudao == "ios" {
				iosprice = iosprice + v.Price
			} else {
				anzhuoprice = anzhuoprice + v.Price
			}
		}
		data := UserffRBody{
			Daytime:     daytimeval,
			Dayprice:    dayprice,
			Iosprice:    iosprice,
			Anzhuoprice: anzhuoprice,
			Weixinprice: weixinprice,
		}
		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"error":   0,
			"success": 200,
			"data":    data,
			"msg":     "ok",
		})
		return
	} else if state == 3 {

		var users []models.Userchongzhi
		data_source.Db.Where("addtime >= ?", daytime).Where("addtime < ?", daytime+86400).Find(&users)

		var uidarr []int64
		for _, v := range users {
			cunzai := 1
			for _, u := range uidarr {
				if u == v.Uid {
					cunzai = 2
				}
			}
			if cunzai == 1 {
				uidarr = append(uidarr, v.Uid)
			}
		}
		var fgnums []UserfglistRBody
		for _, u := range uidarr {
			var num int64
			for _, v := range users {
				if u == v.Uid {
					num = num + 1
				}
			}
			fgnum := UserfglistRBody{
				Uid: u,
				Num: num,
			}
			fgnums = append(fgnums, fgnum)
		}
		var onenum int64
		var twonum int64
		var threenum int64
		var fournum int64
		var fivenum int64
		var exceedfivenum int64
		for _, f := range fgnums {
			if f.Num == 1 {
				onenum = onenum + 1
			} else if f.Num == 2 {
				twonum = twonum + 1
			} else if f.Num == 3 {
				threenum = threenum + 1
			} else if f.Num == 4 {
				fournum = fournum + 1
			} else if f.Num == 5 {
				fivenum = fivenum + 1
			} else {
				exceedfivenum = exceedfivenum + 1
			}
		}

		data := UserfgRBody{
			Daytime:       daytimeval,
			Onenum:        onenum,
			Twonum:        twonum,
			Threenum:      threenum,
			Fournum:       fournum,
			Fivenum:       fivenum,
			Exceedfivenum: exceedfivenum,
		}
		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"error":   0,
			"success": 200,
			"data":    data,
			"msg":     "ok",
		})
		return
	} else if state == 4 {
		var dayhynum int64
		var weekhynum int64
		var monthhynum int64

		weekstart, weekend := WeekIntervalTime(0)
		monthstart, monthend := getCurrentMonthStartAndEnd()
		var users []models.User
		data_source.Db.Where("update_time >= ?", monthstart).Where("update_time < ?", monthend).Find(&users)
		for _, u := range users {
			monthhynum = monthhynum + 1
			if u.UpdateTime >= weekstart && u.UpdateTime < weekend {
				weekhynum = weekhynum + 1
			}
			if u.UpdateTime >= daytime && u.UpdateTime < daytime+86400 {
				dayhynum = dayhynum + 1
			}

		}
		data := UserhyRBody{
			Dayhynum:   dayhynum,
			Weekhynum:  weekhynum,
			Monthhynum: monthhynum,
		}
		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"error":   0,
			"success": 200,
			"data":    data,
			"msg":     "ok",
		})
		return
	} else if state == 5 {
		inttime := request.Inttime
		endtime := request.Endtime
		if inttime == 0 {
			inttime = daytime
		}
		if endtime == 0 {
			endtime = daytime + 86400
		}
		inttimeval := time.Unix(inttime, 0).Format("2006-01-02")
		endtimeval := time.Unix(endtime, 0).Format("2006-01-02")

		var usernum int64
		data_source.Db.Model(&models.User{}).Count(&usernum)

		var userchongzhis []models.Userchongzhi
		data_source.Db.Where("addtime >= ?", inttime).Where("addtime < ?", endtime).Find(&userchongzhis)
		var uidarr []int64
		var price float64
		for _, v := range userchongzhis {
			price = price + v.Price
			cunzai := 1
			for _, u := range uidarr {
				if u == v.Uid {
					cunzai = 2
				}
			}
			if cunzai == 1 {
				uidarr = append(uidarr, v.Uid)
			}
		}
		var averagearup float64
		var buyarup float64
		averagearup = price / float64(usernum)
		buyarup = price / float64(len(uidarr))
		averagearup1 := int64(averagearup * 100)
		buyarup1 := int64(buyarup * 100)

		data := UserarupRBody{
			Daytime:     inttimeval + "——" + endtimeval,
			Averagearup: float64(averagearup1) / 100,
			Buyarup:     float64(buyarup1) / 100,
		}
		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"error":   0,
			"success": 200,
			"data":    data,
			"msg":     "ok",
		})
		return
	}

}

// 本周
func WeekIntervalTime(week int) (startTime1, endTime1 int64) {
	now := time.Now()
	offset := int(time.Monday - now.Weekday())
	//周日做特殊判断 因为time.Monday = 0
	if offset > 0 {
		offset = -6
	}

	year, month, day := now.Date()
	thisWeek := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
	startTime := thisWeek.AddDate(0, 0, offset+7*week).Format("2006-01-02") + " 00:00:00"
	endTime := thisWeek.AddDate(0, 0, offset+6+7*week).Format("2006-01-02") + " 23:59:59"
	layout := "2006-01-02 15:04:05"
	t, err := time.Parse(layout, startTime)
	t1, err := time.Parse(layout, endTime)
	if err != nil {
		fmt.Println("时间解析错误:", err)
		return
	}
	return t.Unix() - 3600*8, t1.Unix() - 3600*8
}

// 本月
func getCurrentMonthStartAndEnd() (startTime, endTime int64) {
	// 获取当前时间
	now := time.Now()

	// 获取本月的第一天
	start := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.Local)

	// 获取下个月的第一天减去一秒，得到本月的最后一秒
	end := start.AddDate(0, 1, 0).Add(-1 * time.Second)

	return start.Unix(), end.Unix()
}
